package win.smartown.android.library.rain;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;

/**
 * Created by Smartown on 2017/7/28.
 */
public class Rain extends ImageView {

    private int index;
    private int deltaX, deltaY;
    private long animDistance;
    private float endScale;
    private Callback callback;

    public Rain(Context context, int index, int deltaX, int deltaY, long animDistance, float endScale, Callback callback) {
        super(context);
        this.index = index;
        this.deltaX = deltaX;
        this.deltaY = deltaY;
        this.animDistance = animDistance;
        this.endScale = endScale;
        this.callback = callback;
    }

    public void startAnimation() {
        ObjectAnimator xAnimator = ObjectAnimator.ofFloat(this, "translationX", getTranslationX(), getTranslationX() + deltaX);
        ObjectAnimator yAnimator = ObjectAnimator.ofFloat(this, "translationY", getTranslationY(), getTranslationY() + deltaY);
        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(this, "scaleX", 1, endScale);
        ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(this, "scaleY", 1, endScale);
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(this, "alpha", 1, 0);
        alphaAnimator.setStartDelay(animDistance / 4);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(animDistance);
        animatorSet.setInterpolator(new AccelerateInterpolator());
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                callback.onAnimFinished(Rain.this, index);
            }
        });
        animatorSet.play(xAnimator).with(yAnimator).with(scaleXAnimator).with(scaleYAnimator).with(alphaAnimator);
        animatorSet.start();
    }

    public interface Callback {

        void onAnimFinished(Rain view, int index);

    }

}
